<template>

  <el-dialog
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :show-close="false"
    title="人脸认证"
    width="540px"
  >
    <div class="face-box">

      <tracking-cam
        v-if="dialogVisible"
        ref="cam"
        :tracking="true"
        @tracked="handleTracked"/>

      <div v-if="faceInfo.faceToken!=null && faceInfo.faceToken!==''" class="scanTip">
        <div>姓名：{{ faceInfo.realName }}</div>
        <div>身份证：{{ faceInfo.idCard }}</div>
        <div>识别成功，请继续下一步操作</div>
      </div>

    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="danger" @click="handleClose">取 消</el-button>
    </div>

  </el-dialog>

</template>

<script>
import { post } from '@/utils/request'
import TrackingCam from '@/components/TrackingCam/index.vue'

export default {
  name: 'FaceCheckDialog',
  components: { TrackingCam },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    params: {
      type: Object,
      default: function() {
        return {}
      }
    },
    url: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      dialogVisible: false,
      faceInfo: {
        id: '',
        realName: '',
        idCard: ''
      }
    }
  },

  watch: {

    // 检测查询变化
    visible: {
      handler() {
        this.dialogVisible = this.visible
      },
      deep: true
    }
  },

  created() {
    this.dialogVisible = this.visible
  },

  methods: {

    // 关闭窗口
    handleClose() {
      this.$message.info('窗口已关闭，若要重新识别请刷新页面！')
      this.$emit('update:visible', false)
    },

    // 拍照
    handleTracked(base64) {
      // 附加base64图片
      const params = this.params
      this.$set(params, 'base64', base64)

      post(this.url, params).then(res => {
        this.faceInfo = res.data
        if (this.faceInfo.pass) {
          this.successBack()
        } else {
          this.failBack(this.faceInfo.failMsg)
        }
      }).catch(this.failBack)
    },

    // 成功回调
    successBack() {
      this.$message.success('人脸比对成功！')
      this.$emit('success', this.faceInfo)
      setTimeout(() => {
        this.$emit('update:visible', false)
      }, 2000)
    },

    // 识别失败
    failBack(msg) {
      this.$emit('fail')
      this.$refs.cam.reTrack()

      // 显示消息
      if (msg) {
        this.$message.error(msg)
      }
    }
  }
}
</script>

<style scoped>

.face-box{
  position: relative;
  width: 100%;
  height: auto;
}

.scanTip{
  margin-top: 10px;
  font-size: 12px;
  font-weight: 500;
  line-height: 20px;
  color: #1AAC1A;
}
</style>
